package main

import (
	"net/http"
	"strconv"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func initWebServer() {
	e := echo.New()
	e.Debug = true

	e.Use(middleware.Logger())
	// e.Use(middleware.Recover())

	e.GET("/savedData", retriveSavedData)
	e.GET("/savedDataBefore", retriveSavedDataBefore)
	e.GET("/savedDataAfter", retriveSavedDataAfter)

	go func() {
		e.Logger.Fatal(e.Start(":" + strconv.FormatInt(int64(conf.WebServerPort), 10)))
	}()
}

// badRequest 返回400
func badRequest(msg ...interface{}) error {
	return echo.NewHTTPError(http.StatusBadRequest, msg...)
}

// retriveSavedData 获取已经被保存的采集卡样本数据（获取某个时间点附近的数据）
func retriveSavedData(c echo.Context) error {
	timeUnix, err := strconv.ParseInt(c.QueryParam("timeUnix"), 10, 64)
	if err != nil {
		return badRequest("timeUnix is not an int64 number, error: " + err.Error())
	}
	targetCount, err := strconv.Atoi(c.QueryParam("targetCount"))
	if err != nil {
		return badRequest("targetCount is not a number, error: " + err.Error())
	}

	sampleSeries, err := retriveDacSamples(time.Unix(timeUnix, 0), targetCount)
	if err != nil {
		c.Logger().Errorf("failed to get dac samples from db, error: %v\n", err)
	}

	return c.JSON(http.StatusOK, sampleSeries)
}

// retriveSavedDataBefore 获取已经被保存的采集卡样本数据（获取某个时间点前的数据）
func retriveSavedDataBefore(c echo.Context) error {
	timeUnixNano, err := strconv.ParseInt(c.QueryParam("timeUnixNano"), 10, 64)
	if err != nil {
		return badRequest("timeUnixNano is not an int64 number, error: " + err.Error())
	}
	alreadyGot, err := strconv.Atoi(c.QueryParam("alreadyGot"))
	if err != nil {
		return badRequest("alreadyGot is not a number, error: " + err.Error())
	}
	targetCount, err := strconv.Atoi(c.QueryParam("targetCount"))
	if err != nil {
		return badRequest("targetCount is not a number, error: " + err.Error())
	}

	sampleSeries, err := retriveDacSamplesBefore(time.Unix(0, timeUnixNano), alreadyGot, targetCount)
	if err != nil {
		c.Logger().Errorf("failed to get dac samples from db, error: %v\n", err)
	}

	return c.JSON(http.StatusOK, sampleSeries)
}

// retriveSavedDataAfter 获取已经被保存的采集卡样本数据（获取某个时间点后的数据）
func retriveSavedDataAfter(c echo.Context) error {
	timeUnixNano, err := strconv.ParseInt(c.QueryParam("timeUnixNano"), 10, 64)
	if err != nil {
		return badRequest("timeUnixNano is not an int64 number, error: " + err.Error())
	}
	alreadyGot, err := strconv.Atoi(c.QueryParam("alreadyGot"))
	if err != nil {
		return badRequest("alreadyGot is not a number, error: " + err.Error())
	}
	targetCount, err := strconv.Atoi(c.QueryParam("targetCount"))
	if err != nil {
		return badRequest("targetCount is not a number, error: " + err.Error())
	}

	sampleSeries, err := retriveDacSamplesAfter(time.Unix(0, timeUnixNano), alreadyGot, targetCount)
	if err != nil {
		c.Logger().Errorf("failed to get dac samples from db, error: %v\n", err)
	}

	return c.JSON(http.StatusOK, sampleSeries)
}
